package com.cfc.stage1;

import org.junit.Test;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;

/**
 * @description: 有效的括号
 *   https://leetcode.cn/problems/valid-parentheses/
 * @author: yangxuan10
 * @create: 2024-04-09 11:44
 **/
public class IsValid {

    @Test
    public void test1() {
        String str = "{[]}";
        System.out.println(isValid(str));
    }

    public boolean isValid1(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }

    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (char indexChar : chars) {
            if ('(' == indexChar || '{' == indexChar || '[' == indexChar) {
                stack.push(indexChar);
            } else {
                if (stack.size() == 0) {
                    return false;
                }
                Character peekChar = stack.peek();
                if (('(' == peekChar && indexChar == ')') ||
                        ('{' == peekChar && indexChar == '}') ||
                        ('[' == peekChar && indexChar == ']')) {
                    stack.pop();
                } else if (('(' == peekChar && (indexChar == ']' || indexChar == '}')) ||
                        ('{' == peekChar && (indexChar == ')' || indexChar == ']')) ||
                        ('[' == peekChar && (indexChar == ')' || indexChar == '}'))) {
                    return false;
                }
            }
        }
        return stack.size() == 0;
    }

}